#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <string>
#include <iostream>
#include <unistd.h>

#define NUM 1024

namespace sxj{
    class tcpclient
    {
        public:
        tcpclient(const std::string& serverip,const uint16_t& serverport)
        :_sock(-1),
        _serverip(serverip),
        _serverport(serverport)
        { }

        void initclient()
        {
            _sock = socket(AF_INET,SOCK_STREAM,0);
            if(_sock < 0)
            {
                std::cerr<<"server create socket error!"<< std::endl;
                exit(-1);
            }
            std::cout<<"server create socket success!"<<std::endl;

            //tcp的客户端要不要bind？  要的！ 要不要显示的bind？ 不要！
            //尤其是client port要让os自己指定
            //客户选需不需要listen？ 不要
            //客户选需不需要accept? 不要
        }
        void start()
        {
            struct sockaddr_in server;
            memset(&server,0,sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());

            if(connect(_sock,(struct sockaddr*)&server,sizeof(server)) < 0)
            {
                std::cerr<<"server socket connect error!"<<std::endl;
            }
            else
            {
                std::string message;
                while(1)
                {
                    std::cout<<"Please Enter:>";
                    std::getline(std::cin,message);
                    write(_sock,message.c_str(),message.size());

                    char buffer[NUM];
                    int n = read(_sock,buffer,sizeof(buffer)-1);
                   if(n>0)
                   {
                        buffer[n] = 0;
                        std::cout<<"server 回显# "<< buffer <<std::endl;
                   }
                   else if(n == 0)
                   {
                        break;
                   }

                }
            }
        }

        

         ~tcpclient()
         {
            if(_sock >=0) close(_sock);
         }
        private:
            int _sock;
            std::string _serverip;
            uint16_t _serverport;
        
    };
}